import React, { Component } from 'react'
//路由传参
import {withRouter} from "react-router-dom"
import {Bottom,InputItem,ImagePicker, WingBlank, SegmentedControl,Toast,TextareaItem} from "antd-mobile"
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import './index.scss'
import OrderVideo from '../../assets/img/order-video.png'
import OrderXj from '../../assets/img/order-xj.png'
import Correct from '../../assets/img/correct.png'
import Error from '../../assets/img/error.png'
import VideoMp4 from '../../assets/img/video.mp4'
import {throttle} from 'throttle-debounce'
import OrderStart from '../../assets/img/11.png'
import axios from 'axios'
import OrderError from '../../assets/img/orderError.png'
import { BASE_URL } from '../../utils/requestPath';
import requestAxios from '../../utils/myaxios'
import Jump from '../../assets/img/navigator_jump.png'
const uploadImage = BASE_URL+"/uploadPictures"
var time;
const data = [];
function getBase64(img, callback){
    console.log("-=-=-=-=-=-=-=-=--=--=")
    console.log(img)
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

//图片
function beforeUpload(file) {
    console.log("----------------------------------------------------------------")
    console.log(file)
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 5; //file.size / 1024 / 1024 < 2 小于2M  
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

//视频
function beforeUploadVideo(file) {
    console.log("----------------------------------------------------------------")
    console.log(file)
    const isJpgOrPng = file.type === 'video/mp4' || file.type === 'video/mp4';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 20; //file.size / 1024 / 1024 < 2 小于2M  
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}


  
function beforeUploadText(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class OrderInformation extends Component {
    
    state = {
        reSet:"<",
        dataflag:0,
        orderInputValue:"",
        message:"",
        files: data,
        multiple: false,
        dataList:[],
        loading: false,
        imagesList:[
          
        ],
        valueList:[

        ],
        canRun:false,
        orderStartImg:false,
        naviagtorOrderStart:false,
        JumpItem:false,
        clearNaviagtorOrderTop:true,
        naviagtorOrderStartTop:true,
        goodsIntegral:false,
        userInfoNew:{},
        orderId:300,
        integralCount:10000,  //积分
        integralGoodCount:1000, //日元
        
    }

    onChange = (files, type, index) => {
        console.log(files, type, index);
        this.setState({
            dataList:files
        });
    }

    onSegChange = (e) => {
        const index = e.nativeEvent.selectedSegmentIndex;
        this.setState({
          multiple: index === 1,
        });
      }

    handleClick = (params) => {
        this.props.history.push("/searchCenter");
    }
    
    escOnClick=()=>{
        this.props.history.goBack()
        //this.props.history.push("/navigator")
    }

    componentDidMount(){
       console.log(parseInt(new Date().getTime()))
       this.requestIntegralOrderJump()
       this.getOrderInfo()
    }

    //查询用户订单信息...
    getOrderInfo= async()=>{

        const userInfoIns =await localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
    
        await requestAxios.get(BASE_URL+"/api/order/info/"+parseInt(user.id)).then(res=>{
           if(!res.data){
               this.setState({
                 integralCount:1000,
                 integralGoodCount:100,
               })
           }else{
            this.setState({
                integralCount:10000,
                integralGoodCount:1000,
              })
           }
        })

        
    
      }

    inputOnClick = ()=>{
        console.log(this.state.orderInputValue)
        requestAxios.get(BASE_URL+"/api/order/find/"+this.state.orderInputValue).then(res=>{
            if(res.data.flag){
                this.setState({
                    dataflag:1,
                    message:res.data.message
                })
            }else{
                this.setState({
                    dataflag:2,
                    message:res.data.message
                })
            }
        })

    }

    //输入的帖子信息....
    InputOrderOnChange = (e)=>{
        this.setState({
            orderInputValue:e
        })

    }
    handleChange = info => {
        console.log("点击了照片")
        console.log(info)
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {

            console.log(info.file.response)
            let {imagesList} = this.state;
            let iamgesListAll = imagesList
            iamgesListAll.push(
                {
                    time:parseInt(new Date().getTime()),
                    url:"http://"+info.file.response
                }
            )
            
            this.setState({
                imagesList:iamgesListAll
            })

            console.log(iamgesListAll)
        }
      };
      handleChangeVideo = info => {
          console.log("点击了video")
        console.log(info)
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {

            console.log(info.file.response)
            let {valueList} = this.state;
            let valueListAll = valueList
            valueListAll.push(
                {
                    time:parseInt(new Date().getTime()),
                    url:"http://"+info.file.response
                }
            )
            
            this.setState({
                valueList:valueListAll
            })

            //push 后的
            console.log(this.state.valueList)
            console.log(this.state.imagesList)
        }
      };

      onClickImages=(e)=>{
          console.log(e)
          console.log("dianji")
          const {imagesList} = this.state;
          imagesList.splice(e,1)
          this.setState({
              imagesList:imagesList
          })
      }

      onClickVideo=(e)=>{
        console.log(e)
        console.log("dianji")
        const {valueList} = this.state;
        valueList.splice(e,1)
        this.setState({
            valueList:valueList
        })
    }

    //发送帖子..........
    onClickStart= async ()=>{
        this.getOrderInfo()
        var dFlag = true;
        //get user info
        const zgUser = localStorage.getItem("userInfoIns");
        const zgUsers = JSON.parse(zgUser) || {};
        //上传的图片,,,用户id,mobx ,,,订单号,,,,,订单提交成功得到多少积分

        
        // imagesList 图片字符串.....
        const {imagesList,orderInputValue} = this.state;
        if(orderInputValue.length <= 0){
            Toast.info('输入有误', 2, null, false);
            return;
        }
        
        var elementImg = ""
        // send community request
        
        for (let i = 0; i < imagesList.length; i++) {

            console.log(imagesList[i].url)

            elementImg += imagesList[i].url + ","
            
        }

        console.log(elementImg)

        //debugger
        const userId = zgUsers.id;
        const comment = orderInputValue;
        const commentImg = elementImg;
        const communityPosts = {userId,comment,commentImg};
        requestAxios.post(BASE_URL+"/api/community/posts/add",communityPosts).then(res=>{
            if(res.data.flag){
                Toast.success('帖子发送成功!!!', 1);
                this.props.history.push("community")
            }
        })

    }
    orderErrorOnClick = ()=>{
        this.setState({
            orderStartImg:false
        })
        console.log("关闭......")
    }

    lwOnClick = ()=>{

        this.props.history.push("/navigator")

    }

    handleChangeText = info => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,
            }),
          );
        }
      };

      onChangeImage = (files, type, index) => {
        console.log(files, type, index);
        this.setState({
          files,
        });
      }

      uploadClick = ()=>{
          console.log("点击了.......")
      }

      

      requestIntegralOrderJump=()=>{
        const userInfoIns = localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
        
        requestAxios.get(BASE_URL+"/api/user/getid/"+user.id).then(res=>{
            //debugger
            if(res.data.jumpStart !== 1){
              this.setState({
                naviagtorOrderStart:true,
                JumpItem:true
              })
            }
        })
      }

      //跳过引导........发送请求...后台,同时关闭页面向导
      clearNaviagtorOrderTop=()=>{
        this.setState({
            JumpItem:false
        })
      }
    
    
      naviagtorOrderStart = ()=>{
          this.setState({
            naviagtorOrderStart:false,
            // clearNaviagtorOrderTop:true,
            // naviagtorOrderStartTop:true,
          })
      }

      //步骤一,用户输入订单号后进行下一步操作
      naviagtorOrderStartTop = ()=>{
          //判断用户是否输入了订单号
          if(this.state.orderInputValue.length > 7){
            this.setState({
                naviagtorOrderStartTop:false,
                orderId:3
            })
          }
      }

      //步骤二,上传图片的下一步
      naviagtorOrderStartTopTwo=()=>{
          console.log(313131)
      }

      //步骤三:提交请求
      naviagtorOrderStartTopThree=()=>{
          console.log(234234)
      }


    render() {
        const {reSet,loading, imageUrl,files} = this.state
        const uploadButton = (
            <div style={{flexDirection:"column",alignItems:"center"}}>
              {/* {loading ? <LoadingOutlined /> : <PlusOutlined />} */}
              <img src={OrderXj} style={{width:40,height:40}}></img>
              <div style={{ marginTop: 8 ,fontWeight:"800"}}>添加照片</div>
            </div>
          );

          const uploadButtonVideo = (
            <div style={{flexDirection:"column",alignItems:"center"}}>
              {/* {loading ? <LoadingOutlined /> : <PlusOutlined />} */}
              <img src={OrderVideo} style={{width:40,height:40}}></img>
              <div style={{ marginTop: 8 ,fontWeight:"800"}}>添加视频</div>
            </div>
          );

          const uploadButtonTexe = (
            <div>
              {loading ? <LoadingOutlined /> : <PlusOutlined />}
              <div style={{ marginTop: 8 }}>Upload</div>
            </div>
          );
        return (
            <div className="main-community-posts-app">
                {/* 头部,返回,评价 */}
                <header className="main-community-posts-header">
                    <div className="main-community-posts-header-con" onClick={this.escOnClick}>
                        <span className="main-community-posts-header-con-span-one">{reSet}</span>
                        <span  className="main-community-posts-header-con-span-two">返回</span>
                    </div>
                    <h4>
                        发送帖子
                    </h4>
                </header>

                {/* 店铺名称.....及订单号 */}
                <main className="main-community-posts-con">
                    {/* 内部内容 */}
                    <section className="main-community-posts-top">
                    {/* 名称及订单号 */}
                    {/* <h4>店铺名称:漫步华尔街</h4> */}
                    <div className="main-community-posts-id">
                         {/* <h4>输入订单号</h4> */}
                         <TextareaItem
                        onChange={this.InputOrderOnChange}
                        placeholder="请输入帖子.........."
                        rows={5}
                        count={100}
                    />
                         {/* <InputItem
                         style={{}}
                            placeholder="请输入帖子.........."
                            labelNumber={100}
                            onChange={this.InputOrderOnChange}
                        ></InputItem> */}
                        
                    </div>
                    {/* <span className="main-community-posts-information-message">请上传您在亚马逊(日本)/乐天/雅虎的订单好评截图,双击添加图片...</span> */}
                    {/* 照片以及添加视频 */}
                    <div className="main-community-posts-img-and-video">
                        <article 
                        onClick={this.uploadClick}
                        className="main-community-posts-img">
                        <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={uploadImage}
                                beforeUpload={beforeUpload}
                                onChange={this.handleChange}
                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%',height:"100%"  }} /> : uploadButton}
                            </Upload>
                        </article>
                    </div>

                    {/* 留个空地址用来存放图片 */}
                    <div className="main-community-posts-imgs">
                       {this.state.imagesList.map((value,index)=>{
                           return (
                               <div key={index} style={{position:"relative",marginLeft:9}}>
                                   <div 
                                   onClick={this.onClickImages.bind(this,index)} 
                                   style={{position:"absolute",right:2,top:2,
                                   display:"block",width:10,height:10,}}
                                   >X</div>
                                   <img style={{width:80,height:80,marginLeft:10,marginBottom:10}} src={value.url}></img>
                               </div>    
                           )
                       })}
                    </div>

                    <div className="main-community-posts-video-list">
                        {this.state.valueList.map((value,index)=>{
                            return (
                                <div key={index} style={{position:"relative",marginLeft:9}}>
                                    <div 
                                    onClick={this.onClickVideo.bind(this,index)} 
                                    style={{position:"absolute",right:2,top:2,
                                    display:"block",width:10,height:10,}}
                                    >X</div>
                                    <video 
                                        autoPlay
                                        style={{width:120,height:120}} 
                                        src={value.url}>
                                    </video>
                                </div>    
                            )
                        })}
                     
                    </div>

                    {/* 如果超过5张..... */}
                    {/* <p>拍摄<span className="span1">5</span>张图片有机会被选为<span className="span2">优质评价</span></p> */}
                    {/* ---------------------------------------------------------- */}

                    {/* 活动规则 */}
                    {/* <div className="main-community-posts-activity-rules">
                        <h2>活动规则</h2>
                        <div className="main-community-posts-activity-right">
                            <h4>1,必须五星好评</h4>
                            <h4>2,评价不许带"好评返现字样"</h4>
                            <h4>3,24小时之内返现</h4>
                        </div>
                    </div> */}
                    </section>

                    {/* 提交请求 */}
                    <div className="footerInputCon" onClick={this.onClickStart}>
                     <input className="footerInput" type="button" value="发送帖子"></input>
                    </div>

                </main>
            </div>
        )
    }
}
export default withRouter(OrderInformation)
